#include "server_h.h"

int main(int argc, char const *argv[])
{
    if(argc!=3){
        printf("Usage:%s<ip><port>\n",argv[0]);
        exit(-1);
    }

    sqlite3 *db=NULL;
    if(sqlite3_open(DBNAME,&db)!=SQLITE_OK){
        printf("数据库打开或创建失败:%s\n",sqlite3_errmsg(db));
    }else{
        printf("数据库打开或创建成功\n");
    }

    //pid_t pid;
    int sockfd=-1;
    int acceptfd=-1;
    pthread_t thread;
    struct client arg;
    struct sockaddr_in servaddr,clientaddr;
    socklen_t addrlen=sizeof(servaddr);

    if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
        ERRLOG("socket error");
    }

    memset(&servaddr,0,addrlen);
    memset(&clientaddr,0,addrlen);
    servaddr.sin_family=AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(argv[1]);
    servaddr.sin_port=htons(atoi(argv[2]));

    if(bind(sockfd,(struct sockaddr*)&servaddr,addrlen)==-1){
        ERRLOG("bind error");
    }

    if(listen(sockfd,5)<0){
        ERRLOG("listen error");
    }

    signal(SIGCHLD,handler);

    while(1){
        if((acceptfd=accept(sockfd,(struct sockaddr*)&clientaddr,&addrlen))==-1){
            ERRLOG("accept error");
        }
#if 0
        if((pid=fork())==-1){
            ERRLOG("fork error");
        }else if(pid>0){
            close(acceptfd);
                     
        }else{
            close(sockfd);
            do_client(acceptfd,db);
        }
#endif

        arg.acceptfd=acceptfd;
        arg.db=db;
        pthread_create(&thread,NULL,pthread_client,&arg);
    }

    return 0;
}
